package com.servlet;

import com.dao.AddDao;
import com.dao.impl.AddDaoImpl;
import com.entity.Users;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/usernameCheck")
public class UsernameCheckServlet extends HttpServlet {
    private AddDao addDao;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        addDao = new AddDaoImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        resp.setContentType("application/json");
        try {
           Users user = addDao.getByUsername(username);
            resp.getWriter().print("{\"exist\": " + (null != user) + "}");
        } catch (Throwable e) {
            resp.getWriter().print("{\"error\": 服务器异常，无法检测用户名!}");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
